import React, { Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Card, Button, Tabs, message, Row, Col, Input, Alert, Select, Modal } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import StandardTable from '@/components/StandardTable';
import downloadFile, { urlParse } from '@/utils/utils';
import Authorized from '@/utils/Authorized';
import TaskProgress from '../../components/TaskProgress';

const FormItem = Form.Item;
const { confirm } = Modal;
const { TabPane } = Tabs;
const { Option } = Select;
@Form.create()
@connect(({ supplybill, supplybilling, loading }) => ({
  supplybill,
  selectMessage: supplybill.selectMessage,
  formFieldsValue: supplybill.formFieldsValue,
  isdefaultFlag: supplybill.isdefaultFlag,
  wageGenerationData: supplybilling.wageGenerationData,
  onceData: supplybilling.onceData,
  otherData: supplybilling.otherData,
  loading: loading.models.supplybilling,
  supplybilling,
}))
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      sendSuppId: '',
      billId: '',
      feeYm: '',
      billYm: '',
      nowPage: 1,
      pageNum: 10,
      activeKey: '3',
      enterActiveKey: '1',
      NA_BILL_UN_CAUSE: [], // 不符合原因的下拉字典
      selectedRowKeys: [],
      selectedRows: [],
      contId: null,
    };
  }

  componentDidMount() {
    const {
      location: { search },
      dispatch,
    } = this.props;
    const { billId, billYm, sendSuppId, enterActiveKey } = this.state;
    const billIdNew = urlParse(search).billId || billId;
    const feeYmNew = urlParse(search).billYm || billYm;
    const sendSuppIdNew = urlParse(search).sendSuppId || sendSuppId;
    const enterActiveKeyNew = urlParse(search).enterActiveKey || enterActiveKey;
    const contId = urlParse(search).contId || null;

    // 获取字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['NA_BILL_UN_CAUSE'],
      callback: res => {
        this.setState({
          NA_BILL_UN_CAUSE: res.NA_BILL_UN_CAUSE,
        });
      },
    });

    this.setState(
      {
        billId: billIdNew,
        feeYm: feeYmNew,
        billYm: feeYmNew,
        sendSuppId: sendSuppIdNew,
        enterActiveKey: enterActiveKeyNew,
        contId: contId === 'undefined' ? null : contId,
      },
      () => {
        this.getList(1, 10);
      }
    );
  }

  // 查看当前有无任务
  checkHasTask = () => {
    const { dispatch } = this.props;
    // 查看当前有无任务进行
    dispatch({
      type: 'supplybill/checkCreateBillTask',
    });
  };

  // 进度弹框显隐
  handleProgressModalVisible = flag => {
    const { dispatch } = this.props;
    if (!flag) {
      dispatch({
        type: 'supplybilling/updateModelData',
        payload: {
          showProgress: false,
        },
      });
    }
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize);
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    if (selectedRowKeys.length > 100) {
      message.warning('勾选数据不能超过100条');
    } else {
      this.setState({ selectedRowKeys, selectedRows });
    }
  };

  // 切换是否符合
  handleSizeChange = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'supplybill/defaultFlagModelData',
      payload: {
        // selectMessage: [],
        isdefaultFlag: e,
      },
    });
    this.setState({
      selectedRowKeys: [],
      selectedRows: [],
    });
  };

  // 获取列表数据
  getList = (nowPage, pageNum) => {
    const { formFieldsValue, dispatch } = this.props;
    const { activeKey, sendSuppId, billYm, enterActiveKey, contId } = this.state;
    const pageArg = {
      currentPage: nowPage,
      pageSize: pageNum,
    };

    let pldata = {
      sendSuppId,
      contId,
      billYm,
      pageArg,
      creType: enterActiveKey,
      unnaturalCause: formFieldsValue.unnaturalCause || null,
      cardNo: formFieldsValue.cardNo || null,
      empName: formFieldsValue.empName || null,
      defaultFlag: formFieldsValue.defaultFlag,
    };
    switch (activeKey) {
      case '1': // 代发工资代收费
        pldata = {
          sendSuppId,
          billYm,
          pageArg,
          creType: enterActiveKey,
          contId,
        };
        dispatch({
          type: 'supplybilling/getWageGenerationList',
          payload: pldata,
        });
        break;
      case '2': // 一次性收费
        pldata = {
          sendSuppId,
          billYm,
          pageArg,
          creType: enterActiveKey,
          contId,
        };
        dispatch({
          type: 'supplybilling/getOnceList',
          payload: pldata,
        });
        break;
      case '3': // 其它
        pldata = {
          sendSuppId,
          billYm,
          pageArg,
          creType: enterActiveKey,
          unnaturalCause: formFieldsValue.unnaturalCause || null,
          cardNo: formFieldsValue.cardNo || null,
          empName: formFieldsValue.empName || null,
          defaultFlag: formFieldsValue.defaultFlag,
          contId,
        };
        dispatch({
          type: 'supplybilling/getOtherList',
          payload: pldata,
        });
        break;
      default:
        pldata = {
          sendSuppId,
          pageArg,
          creType: enterActiveKey,
          unnaturalCause: formFieldsValue.unnaturalCause || null,
          cardNo: formFieldsValue.cardNo || null,
          empName: formFieldsValue.empName || null,
          defaultFlag: formFieldsValue.defaultFlag,
          contId,
        };
        dispatch({
          type: 'supplybilling/getOtherList',
          payload: pldata,
        });
        break;
    }
  };

  // 切换页签
  changeTabPane = activeKey => {
    const { nowPage, pageNum } = this.state;
    const { form, dispatch, formFieldsValue, isdefaultFlag } = this.props;
    form.resetFields();
    if (formFieldsValue.defaultFlag === isdefaultFlag) {
      dispatch({
        type: 'supplybill/updateModelData',
        payload: { selectMessage: [] },
      });
    } else {
      dispatch({
        type: 'supplybill/updateModelData',
        payload: { selectMessage: [], isdefaultFlag: formFieldsValue.defaultFlag },
      });
    }
    this.setState({ activeKey, nowPage: 1, selectedRowKeys: [], selectedRows: [] }, () => {
      this.getList(nowPage, pageNum);
    });
  };

  // //列表搜索
  searchList = () => {
    const { form, dispatch } = this.props;
    const { cusName, feeYm, tabpaneid } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        dispatch({
          type: 'supplybill/updateModelData',
          payload: {
            formFieldsValue: values,
          },
        });
        this.setState({ nowPage: 1, pageNum: 10 });
        setTimeout(() => {
          this.getList(1, 10, cusName, feeYm, tabpaneid);
        }, 0);
      }
    });
  };

  isBack = () => {
    router.goBack();
  };

  // 生成账单
  toBill = () => {
    const { dispatch, selectMessage, form, formFieldsValue } = this.props;
    const { enterActiveKey, billYm, selectedRowKeys, sendSuppId, contId } = this.state;
    const result = [];
    const obj = {};
    for (let i = 0; i < selectMessage.length; i += 1) {
      if (!obj[selectMessage[i].key]) {
        result.push(selectMessage[i]);
        obj[selectMessage[i].key] = true;
      }
    }
    const newSelect = [];
    result.map(item => {
      selectedRowKeys.map(sitem => {
        if (item.key === sitem) {
          newSelect.push(item);
        }
        return true;
      });
      return true;
    });
    let subdData = null;
    form.validateFieldsAndScroll((err, values) => {
      const temp = values;
      temp.unnaturalCause = formFieldsValue.unnaturalCause || null;
      temp.defaultFlag = formFieldsValue.defaultFlag || null;
      temp.empName = formFieldsValue.empName || null;
      temp.cardNo = formFieldsValue.cardNo || null;
      subdData = values;
    });
    const newSubData = [];
    selectedRowKeys.map(seitem => {
      const i = seitem.split('^');
      const iitem = {
        cardNo: i[0] === 'undefined' ? null : i[0], // 身份证
        custId: i[1] === 'undefined' ? null : i[1], // 客户id
        empId: i[2] === 'undefined' ? null : i[2], // 员工id
        feeYm: i[3] === 'undefined' ? null : i[3], // 收费年月
        sendSuppId: i[4] === 'undefined' ? null : i[4], // 签约方
        defaultFlag: i[5] === 'undefined' ? null : i[5], // 标识
        unnaturalCause: i[6] === 'undefined' ? null : i[6], // 不符合进账单原因
      };
      newSubData.push(iitem);
      return true;
    });
    const submitData = {
      condList: newSubData,
      sendSuppId,
      contId: contId === 'undefined' ? null : contId,
      ...subdData,
    };
    if (newSubData.length === 0) {
      confirm({
        icon: <QuestionCircleOutlined />,
        title: '温馨提示',
        content:
          '工资和一次性费用会全部生成；其它页签中不勾选数据时，将查询所有数据生成账单；勾选数据，只将勾选数据生成账单，是否确定生成账单？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          dispatch({
            type: 'supplybilling/uploadFileWithProgress',
            payload: {
              batchType: enterActiveKey === '1' ? 3 : 4,
              params: { billYm, ...submitData },
            },
          });
        },
      });
    } else {
      dispatch({
        type: 'supplybilling/uploadFileWithProgress',
        payload: {
          batchType: enterActiveKey === '1' ? 3 : 4,
          params: { billYm, ...submitData },
        },
      });
    }
  };

  // 导出
  export = () => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      Modal.confirm({
        icon: <QuestionCircleOutlined />,
        title: '温馨提示',
        content: '如果不选择列表数据，则默认导出当前条件下所有数据',
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          this.exportExcel();
        },
      });
    } else {
      this.exportExcel();
    }
  };

  // 导出excel
  exportExcel = () => {
    const { formFieldsValue } = this.props;
    const { selectedRowKeys, selectedRows, sendSuppId, billYm, contId } = this.state;
    const newcondList = [];
    selectedRows.forEach(item => {
      newcondList.push({
        custId: item.custId || null,
        sendSuppId: item.sendSuppId || null,
        feeYm: item.feeYm || null,
        empId: item.empId || null,
        defaultFlag: item.defaultFlag || null,
        unnaturalCause: item.unnaturalCause || null,
      });
    });
    const params = {
      sendSuppId,
      billYm,
      contId,
      ...formFieldsValue,
      condList: !selectedRowKeys ? [] : newcondList,
    };
    downloadFile(params, '/csApi/nsBill/exportNoBillDet', 'POST');
  };

  render() {
    const {
      supplybilling,
      formFieldsValue,
      form: { getFieldDecorator },
      isdefaultFlag,
      wageGenerationData,
      onceData,
      otherData,
      loading,
    } = this.props;
    const { NA_BILL_UN_CAUSE, selectedRows, selectedRowKeys } = this.state;
    const formItemLayoutStyles = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 15 } },
    };

    const columnsWage = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '证件号',
        dataIndex: 'cardNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '是否垫付',
        dataIndex: 'isSpotName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '个人所得税',
        dataIndex: 'taxblAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'right' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
      },
      {
        title: '实发工资',
        dataIndex: 'realAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'right' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
      },
      {
        title: '工资年月',
        dataIndex: 'busiYm',
        align: 'center',
        sorter: (a, b) => new Date(b.busiYm) - new Date(a.busiYm),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      },
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
    ];
    const columnsOnce = [
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      // {
      //   title: '收费年月',
      //   dataIndex: 'feeYm',
      //   sorter: (a, b) => new Date(b.feeYm) - new Date(a.feeYm),
      //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      //   render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      // },
      {
        title: '业务年月',
        dataIndex: 'busiYm',
        sorter: (a, b) => new Date(b.busiYm) - new Date(a.busiYm),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      },
      {
        title: '金额',
        dataIndex: 'feeAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'right' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
      },
      {
        title: '产品',
        dataIndex: 'pdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
    ];
    const columnsOthers = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '证件号',
        dataIndex: 'cardNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      // {
      //   title: '收费年月',
      //   dataIndex: 'feeYm',
      //   sorter: (a, b) => new Date(b.feeYm) - new Date(a.feeYm),
      //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      //   render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      // },
      {
        title: '金额',
        dataIndex: 'realFeeAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'right' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
      },
      {
        title: '是否符合',
        dataIndex: 'defaultFlagName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'right' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
      },
      {
        title: '不符合原因',
        dataIndex: 'unnaturalCauseName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'right' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
      },

      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
    ];

    return (
      <PageHeaderWrapper>
        <Card style={{ marginBottom: 24 }} bordered={false}>
          <Tabs defaultActiveKey="3" onChange={this.changeTabPane}>
            <TabPane tab="代发工资待报税" key="1">
              <StandardTable
                selectedRows={selectedRows}
                selectedRowKeys={selectedRowKeys}
                loading={loading}
                data={wageGenerationData}
                rowKey="key"
                columns={columnsWage}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
                rowSelection={null}
              />
            </TabPane>
            <TabPane tab="一次性收费" key="2">
              <StandardTable
                selectedRows={selectedRows}
                selectedRowKeys={selectedRowKeys}
                loading={loading}
                data={onceData}
                rowKey="key"
                columns={columnsOnce}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
                rowSelection={null}
              />
            </TabPane>
            <TabPane tab="其它" key="3">
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={8} sm={24}>
                  <FormItem {...formItemLayoutStyles} label="姓名">
                    {getFieldDecorator('empName', {
                      rules: [{ required: false }],
                      initialValue: formFieldsValue.empName,
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <FormItem {...formItemLayoutStyles} label="证件号">
                    {getFieldDecorator('cardNo', {
                      rules: [{ required: false }],
                      initialValue: formFieldsValue.cardNo,
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
                <Col md={8} sm={24}>
                  <FormItem {...formItemLayoutStyles} label="是否符合">
                    {getFieldDecorator('defaultFlag', {
                      rules: [{ required: false }],
                      initialValue: formFieldsValue.defaultFlag,
                    })(
                      <Select
                        placeholder="请选择"
                        style={{ width: '100%' }}
                        onChange={this.handleSizeChange}
                      >
                        <Option key="0">全部</Option>
                        <Option key="1">符合</Option>
                        <Option key="2">不符合</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
              </Row>

              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                {isdefaultFlag === '2' ? (
                  <Col md={8} sm={24}>
                    <FormItem {...formItemLayoutStyles} label="不符合原因">
                      {getFieldDecorator('unnaturalCause', {
                        rules: [{ required: false }],
                        initialValue: formFieldsValue.unnaturalCause,
                      })(
                        <Select
                          placeholder="请选择"
                          style={{ width: '100%' }}
                          // onChange={this.noConformity}
                          allowClear
                        >
                          {NA_BILL_UN_CAUSE.map(item => (
                            <Option key={item.itemCode}>{item.itemName}</Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                ) : (
                  <Col md={8} sm={24} />
                )}
                <Col md={8} sm={24} />
                <Col md={7} sm={24}>
                  <div style={{ overflow: 'hidden' }}>
                    <span style={{ float: 'right', marginBottom: 16 }}>
                      <Button type="primary" onClick={this.searchList}>
                        查询
                      </Button>
                    </span>
                  </div>
                </Col>
              </Row>
              <div style={{ width: '100%', marginBottom: 16 }}>
                <Button type="primary" onClick={() => this.export()}>
                  导出
                </Button>
              </div>
              <div style={{ width: '100%', float: 'left' }}>
                <Alert
                  message={
                    <Fragment>
                      此页签包含除代发工资代报税和一次性费用之外的所有费用，例如社保、公积金和服务费等
                    </Fragment>
                  }
                  type="info"
                  showIcon
                />
              </div>
              <Row>
                <Col xl={{ span: 24 }} lg={{ span: 24 }} sm={{ span: 24 }} xs={{ span: 24 }}>
                  <Row gutter={32}>
                    <Col xl={{ span: 24 }} lg={{ span: 24 }} sm={{ span: 24 }} xs={{ span: 24 }} />
                  </Row>
                  <StandardTable
                    selectedRows={selectedRows}
                    selectedRowKeys={selectedRowKeys}
                    loading={loading}
                    data={otherData}
                    rowKey="key"
                    columns={columnsOthers}
                    onSelectRow={this.handleSelectRows}
                    onChange={this.handleStandardTableChange}
                  />
                </Col>
              </Row>
            </TabPane>
          </Tabs>
        </Card>
        <TaskProgress
          progressVisible={supplybilling.showProgress}
          progressPercent={supplybilling.progressPercent || 0}
          isShowResult={supplybilling.progressPercent === 100}
          resultInfo={supplybilling.resultInfo}
          checkHasTask={this.checkHasTask}
          handleProgressModalVisible={this.handleProgressModalVisible}
          closeModalCallBack={() => {
            router.push('/chargemanage/supplybilling/index');
          }}
        />
        <FooterToolbar style={{ width: '100%' }}>
          <Button style={{ marginRight: 10 }} onClick={() => this.isBack()}>
            关闭
          </Button>
          <Authorized authority="cs:nsBill:createBill" noMatch={null}>
            <Button type="primary" onClick={this.toBill}>
              生成账单
            </Button>
          </Authorized>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}
export default BasicList;
